package com.xc.sys.controller;

import com.beust.jcommander.internal.Lists;
import com.xc.common.object.LayuiTableResponse;
import com.xc.common.object.PageInfo;
import com.xc.common.tool.Helper;
import com.xc.db.tables.BaseAttachment;
import com.xc.sys.entity.BaseAttachmentEntity;
import com.xc.sys.entity.SysUserEntity;
import com.xc.sys.service.BaseAttachmentService;
import com.xc.sys.service.SysUserService;
import com.xc.sys.vo.BaseAttachmentVO;
import com.xc.sys.vo.SysUserVO;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jooq.Condition;
import org.jooq.tools.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping({ "/baseAttachment" })
public class BaseAttachmentController {
	@Value("${env.filedir}")
    private String filedir;
	@Autowired
	private BaseAttachmentService baseAttachmentService;
	private BaseAttachment BASEATTACHMENT = BaseAttachment.BASE_ATTACHMENT.as("BASEATTACHMENT");
	@RequestMapping({ "/getPageList" })
	public LayuiTableResponse<BaseAttachmentVO> getPageList(Integer limit,
			Integer page, HttpServletRequest request) {
		String fid = request.getParameter("fid");
		LayuiTableResponse<BaseAttachmentVO> ltr = new LayuiTableResponse<>();
		Condition cond = BASEATTACHMENT.ID.isNotNull();
		if(StringUtils.isNotEmpty(fid)) {
			cond = cond.and(BASEATTACHMENT.FID.eq(fid));
		}
		Long count = this.baseAttachmentService.count(cond);
		PageInfo<BaseAttachmentEntity> pageInfo = new PageInfo<>(limit, page);
		ltr.setCount(count);
		baseAttachmentService.select(cond, pageInfo, BASEATTACHMENT.CREATE_TIME.desc());
		List<BaseAttachmentVO> list = convertEntity2Vo(pageInfo.getList());
		ltr.setData(list);
		return ltr;
	}
	@CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
	@RequestMapping({ "/getList" })
	public LayuiTableResponse<BaseAttachmentVO> getList( HttpServletRequest request) {
		String entityId = request.getParameter("entityId");
		LayuiTableResponse<BaseAttachmentVO> ltr = new LayuiTableResponse<>();
		Condition cond = BASEATTACHMENT.ID.isNotNull();
		if(StringUtils.isNotEmpty(entityId)) {
			cond = cond.and(BASEATTACHMENT.FID.eq(entityId));
		}
		List<BaseAttachmentVO> list = baseAttachmentService.selectVo(cond, BASEATTACHMENT.CREATE_TIME.desc());
		ltr.setData(list);
		return ltr;
	}
	@CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
	@RequestMapping({ "/getPhotos" })
	public LayuiTableResponse<HashMap<String,String>> getPhotos( HttpServletRequest request) {
		String entityId = request.getParameter("entityId");
		LayuiTableResponse<HashMap<String,String>> ltr = new LayuiTableResponse<>();
		Condition cond = BASEATTACHMENT.ID.isNotNull();
		if(StringUtils.isNotEmpty(entityId)) {
			cond = cond.and(BASEATTACHMENT.FID.eq(entityId));
		}
		
		List<HashMap<String,String>> list2 = new ArrayList<>();
		List<BaseAttachmentVO> list = baseAttachmentService.selectVo(cond, BASEATTACHMENT.CREATE_TIME.desc());
		for(BaseAttachmentVO vo : list) {
			HashMap<String,String> map = new HashMap<>();
			map.put("src", vo.getFiledir()+vo.getRepoName());
			map.put("pid", vo.getId());
			list2.add(map);
		}
		ltr.setData(list2);
		return ltr;
	}
	@RequestMapping({ "/showPic" })
	public LayuiTableResponse<HashMap<String,String>> showPic( HttpServletRequest request) {
		String src = request.getParameter("src");
		LayuiTableResponse<HashMap<String,String>> ltr = new LayuiTableResponse<>();
		
		List<HashMap<String,String>> list2 = new ArrayList<>();
		HashMap<String,String> map = new HashMap<>();
		map.put("src", src);
		map.put("pid", "1");
		list2.add(map);
		ltr.setData(list2);
		return ltr;
	}


	@RequestMapping({ "/getById" })
	public BaseAttachmentVO getById(String id) {
		
		BaseAttachmentVO entity = baseAttachmentService.getBoById(id);
		return entity;
	}
	@RequestMapping({ "/save" })
	public LayuiTableResponse<BaseAttachmentEntity> save(BaseAttachmentEntity entity, HttpServletRequest request) {
		BaseAttachmentEntity entity2 = baseAttachmentService.getEntityById(entity.getId());
		entity2.setName(entity.getName());
		entity2.setDescs(entity.getDescs());
		this.baseAttachmentService.save(entity2);
		LayuiTableResponse<BaseAttachmentEntity> ltr = new LayuiTableResponse<>();
		ltr.setId(entity.getId());
		return ltr;
	}
	@RequestMapping({ "/delete" })
	@Transactional
	public List<BaseAttachmentVO> delete(@RequestParam("ids[]") String[] ids) {
		String entityId = "";
		for (String id : ids) {
			BaseAttachmentVO att = BaseAttachmentService.getFrameCaches(id);
			entityId = att.getFid();
			baseAttachmentService.deleteById(id);
		}
		List<BaseAttachmentVO> atts = baseAttachmentService.selectVo(BASEATTACHMENT.FID.eq(entityId),BASEATTACHMENT.CREATE_TIME.desc());
		return atts;
	}
	private List<BaseAttachmentVO> convertEntity2Vo(List<BaseAttachmentEntity> list){
		List<BaseAttachmentVO> list2 = Lists.newArrayList();
		for (BaseAttachmentEntity entity : list) {
			BaseAttachmentVO vo = new BaseAttachmentVO();
			SysUserVO user = SysUserService.getFrameCaches(entity.getCreateUserId());
			vo.setCreateUserName(user==null?"":user.getName());
			vo.setSizeDesc(Helper.convertFileSize(entity.getSize()));
			vo.setName(entity.getName());
			vo.setCreateTime(entity.getCreateTime());
			vo.setId(entity.getId());
			vo.setModel(entity.getModel());
			vo.setFid(entity.getFid());
			vo.setDescs(entity.getDescs());
			vo.setBrand(entity.getBrand());
			vo.setCategory(entity.getCategory());
			list2.add(vo);
		}
		return list2;
	}
	@CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.POST})
	@SuppressWarnings("unchecked")
	@RequestMapping({ "/upload" })
	@Transactional
	public JSONObject upload(MultipartFile[] file,HttpServletRequest request) {
		JSONObject res = new JSONObject();
		String name = request.getParameter("name");
		SysUserEntity me = (SysUserEntity) request.getSession().getAttribute("me");
		res.put("code", 0);
		res.put("msg", "附件上传成功");
		for(MultipartFile doc : file) {
			String fileOriginalName = doc.getOriginalFilename();
			String sufix = Helper.getFullSuffix(fileOriginalName);
			String id = Helper.getSnowId() + "";
			String file_name = request.getParameter("name");
			String zipFieldName = request.getParameter("zip_field_name");
			String descs = request.getParameter("descs");
			file_name = StringUtils.isEmpty(file_name) ? fileOriginalName.replace(sufix, "") : file_name;
			String tableName = request.getParameter("table_name");
			if(tableName!=null&&tableName.equals("")) {
				tableName = null;
			}
			String fid = request.getParameter("fid");
			String userId = me.getId();
			DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyMMdd");
			String dstr = fmt.format(LocalDate.now());//.toString("yyMMdd");
			String rela = "meeting" +File.separator + dstr + File.separator;
			String tempFilePath = filedir+File.separator + rela;
			File tempFileDir = new File(tempFilePath);
			if(!tempFileDir.exists()) {
				try {
					FileUtils.forceMkdir(tempFileDir);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			String fileName = id + sufix;
			String filePath = tempFilePath + File.separator + fileName;
			BaseAttachmentEntity att = new BaseAttachmentEntity();
			att.setCreateTime(LocalDateTime.now());
			att.setCreateUserId(userId);
			att.setFid(fid);
			att.setExt(sufix);
			att.setFiledir(rela);
			att.setDescs(descs);
			att.setName((name==null||name.isEmpty())?doc.getOriginalFilename():name);
			att.setTableName(tableName);
			att.setZipFieldName(zipFieldName);
			att.setRepoName(fileName);
			att.setSize(doc.getSize());
			baseAttachmentService.insert(att);
			File destFile = new File(filePath);
			try {
				doc.transferTo(destFile);
				
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
//		res.put("tid", att.getFid());
		return res;
	}
}
